package com.yixun.qfbao.utils;

import com.yixun.qfbao.config.M2ApiConfig;
import com.yixun.qfbao.model.PartnerInfo;
import com.yixun.qfbao.util.RedisUtil;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class LoginUtils {
	private static final Logger log = LoggerFactory.getLogger(LoginUtils.class);
	
	@Autowired
	private M2ApiConfig m2ApiConfig;
	
	public void putUser(PartnerInfo partnerInfo) {
		try {
			RedisUtil.set(String.valueOf(partnerInfo.getId()), partnerInfo);
		} catch (Exception e) {
			log.info("用户缓存失败:", e);
		}
	}
	
	public void putCache(Object key, Object object) {
		try {
			RedisUtil.set(String.valueOf(key), object);
		} catch (Exception e) {
			log.info("用户缓存失败:", e);
		}
	}
	
	public void removeUser(Object key) {
		try {
			RedisUtil.delete(String.valueOf(key));
		} catch (Exception e) {
			log.info("用户缓存失败:", e);
		}
	}
	
	public PartnerInfo getUser(Object key) {
		PartnerInfo partnerInfo = null;
		try {
			partnerInfo = RedisUtil.get(String.valueOf(key), PartnerInfo.class);
		} catch (Exception e) {
			log.info("获取用户缓存失败:", e);
			return null;
		}
		return partnerInfo;
		
	}
	
	public void put(String key, Object object) {
		try {
			RedisUtil.set(key, object);
		} catch (Exception e) {
			log.error("用户缓存失败: {}", e);
		}
	}

    /**
     * 全局微信accessToken是统一的，由于有两处过期时间处理不一致，这里统一了过期时间
     * @param key
     * @param object
     */
	public void putJsTickeToken(String key, Object object) {
	    try {
            RedisUtil.set(key, object);
            RedisUtil.expire(key, 5000L, TimeUnit.SECONDS);
        } catch (Exception e) {
	        log.error("putJsTickeToken: {}", e);
        }
    }
	
	public Object get(Object key){
		try {
			RedisUtil.get(String.valueOf(key));
		} catch (Exception e) {
			log.error("查询缓存失败,KEY= {}", e);
		}
		return null;
	}

	public void remove(Object key) {
		try {
			RedisUtil.delete(String.valueOf(key));
		} catch (Exception e) {
			log.error("清除缓存: {}", e);
		}
	}
	
	// 清空h5缓存
	public String clearCacheForH5(Long userId) {
		PartnerInfo p = new PartnerInfo();
		p.setId(userId);
		JSONObject jsonObject = JSONObject.fromObject(p);
		String url = m2ApiConfig.getH5RequestUrl() + "/member/loginOutByDelete.do";
		String result = HttpApi.doPost(url, jsonObject.toString());
		log.info("clearCacheForH5 --> url: {}, params: {}, result: {}", url, jsonObject.toString(), result);
		return result;
		
	}
	
}
